<template>
  <view class="edit-page notice-edit-page">
    <!-- 表单内容 -->
    <view class="form-content">
      <uni-forms
          ref="formRef"
          :modelValue="form"
          :rules="rules"
          labelWidth="100px">

        <uni-forms-item label="公告标题" name="noticeTitle" required>
          <uni-easyinput
              v-model="form.noticeTitle"
              placeholder="请输入公告标题"
              :clearable="true"
              :disabled="!canEdit">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="公告类型" name="noticeType" required>
          <BottomSelect
              v-model="form.noticeType"
              :options="noticeTypeOptions"
              :disabled="!canEdit"
              placeholder="请选择公告类型"
              title="选择公告类型">
          </BottomSelect>
        </uni-forms-item>

        <uni-forms-item label="公告内容" name="noticeContent" required>
          <uni-easyinput
              v-model="form.noticeContent"
              type="textarea"
              placeholder="请输入公告内容"
              :auto-height="true"
              :disabled="!canEdit">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="状态" name="status">
          <BottomSelect
              v-model="form.status"
              :options="statusOptions"
              :disabled="!canEdit"
              placeholder="请选择状态"
              title="选择状态">
          </BottomSelect>
        </uni-forms-item>
      </uni-forms>
    </view>

    <!-- 底部操作按钮 -->
    <view class="footer-actions">
      <view class="action-buttons">
        <view
            v-if="!isView"
            class="cancel-btn"
            @click="handleBack">
          取消
        </view>
        <view
            v-if="!isView"
            class="submit-btn"
            @click="handleSubmit">
          {{ pageType === 'add' ? '确认新增' : '保存修改' }}
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import {computed, getCurrentInstance, onMounted, reactive, ref} from 'vue'
import {onLoad} from '@dcloudio/uni-app'
import {addNotice, getNotice, updateNotice} from '@/api/system/notice'
import BottomSelect from '@/components/select/BottomSelect.vue'

const {proxy} = getCurrentInstance()

// 页面参数
const mode = ref('add')
const noticeId = ref('')
const submitting = ref(false)

// 计算属性
const pageTitle = computed(() => {
  switch (mode.value) {
    case 'add':
      return '新增公告'
    case 'edit':
      return '编辑公告'
    case 'view':
      return '查看公告'
    default:
      return '公告管理'
  }
})

const isEdit = computed(() => mode.value === 'edit')
const isView = computed(() => mode.value === 'view')
const canEdit = computed(() => mode.value === 'add' || mode.value === 'edit')

// 编辑器状态
const editorReady = ref(false)
const editorCtx = ref(null)
const formats = ref({})
const placeholder = '请输入公告内容，支持富文本格式...'
const wordCount = ref(0)
const textareaWordCount = ref(0)
const supportEditor = ref(true)

// 表单数据
const form = reactive({
  noticeId: undefined,
  noticeTitle: '',
  noticeType: '',
  noticeContent: '',
  status: '0'
})

// 表单验证规则
const rules = reactive({
  noticeTitle: {
    rules: [
      {required: true, errorMessage: '请输入公告标题'},
      {minLength: 2, errorMessage: '公告标题至少2个字符'},
      {maxLength: 50, errorMessage: '公告标题不能超过50个字符'}
    ]
  },
  noticeType: {
    rules: [
      {required: true, errorMessage: '请选择公告类型'}
    ]
  },
  noticeContent: {
    rules: [
      {required: true, errorMessage: '请输入公告内容'},
      {minLength: 5, errorMessage: '公告内容至少5个字符'}
    ]
  }
})

// 选项数据
const noticeTypeOptions = ref([
  {value: '1', text: '通知'},
  {value: '2', text: '公告'}
])

const statusOptions = ref([
  {value: '0', text: '正常'},
  {value: '1', text: '关闭'}
])

const formRef = ref()

// ==================== 修复：使用 onLoad 生命周期钩子 ====================
onLoad((options) => {

  mode.value = options.mode || 'add'

  if (options.mode === 'edit' && options.noticeId) {
    noticeId.value = options.noticeId
    getNoticeInfo()
  } else if (options.mode === 'view' && options.noticeId) {
    noticeId.value = options.noticeId
    getNoticeInfo()
  }

  // 设置页面标题
  const titleMap = {
    add: '新增公告',
    edit: '编辑公告',
    view: '查看公告'
  }
  uni.setNavigationBarTitle({
    title: titleMap[mode.value] || '公告管理'
  })
})

// 页面加载
onMounted(() => {
  checkEditorSupport()
})

// 检查编辑器支持
function checkEditorSupport() {
  // #ifdef H5 || MP-WEIXIN
  // 在某些平台可能不支持editor组件，使用降级方案
  const systemInfo = uni.getSystemInfoSync()
  if (systemInfo.platform === 'devtools') {
    supportEditor.value = false
  }
  // #endif
}

// 获取公告信息
async function getNoticeInfo() {
  try {
    const response = await getNotice(noticeId.value)
    if (response.code === 200) {
      Object.assign(form, response.data)

      // 设置编辑器内容
      if (editorReady.value && editorCtx.value) {
        editorCtx.value.setContents({
          html: form.noticeContent
        })
      }
    } else {
      proxy.$modal.showToast(response.msg || '获取公告信息失败')
    }
  } catch (error) {
    console.error('获取公告信息失败:', error)
    proxy.$modal.showToast('获取公告信息失败')
  }
}

// 编辑器事件处理
function onEditorReady() {
  editorReady.value = true
  uni.createSelectorQuery().select('#editor').context((res) => {
    editorCtx.value = res.context

    // 如果是编辑模式且有内容，设置编辑器内容
    if (isEdit.value && form.noticeContent) {
      editorCtx.value.setContents({
        html: form.noticeContent
      })
    }
  }).exec()
}

function onEditorFocus() {
  console.log('编辑器获得焦点')
}

function onEditorBlur() {
  console.log('编辑器失去焦点')
}

function onEditorInput(e) {
  // 更新表单内容
  form.noticeContent = e.detail.html

  // 更新字数统计
  const text = e.detail.text || ''
  wordCount.value = text.length
}

function onStatusChange(e) {
  formats.value = e.detail
}

// 文本域事件处理
function onTextareaInput(e) {
  form.noticeContent = e.detail.value
  textareaWordCount.value = e.detail.value.length
}

// 格式化文本
function formatText(format, value) {
  if (!editorCtx.value) return

  editorCtx.value.format(format, value)
}

// 插入图片
function insertImage() {
  uni.chooseImage({
    count: 1,
    sourceType: ['album', 'camera'],
    success: (res) => {
      const tempFilePath = res.tempFilePaths[0]

      // 这里应该上传图片到服务器
      // 暂时使用本地路径
      if (editorCtx.value) {
        editorCtx.value.insertImage({
          src: tempFilePath,
          alt: '图片',
          width: '80%'
        })
      }
    }
  })
}

// 清除格式
function clearFormat() {
  if (editorCtx.value) {
    editorCtx.value.removeFormat()
  }
}

// 提交表单
async function handleSubmit() {
  if (submitting.value) return

  try {
    // 表单验证
    const valid = await formRef.value.validate()
    if (!valid) return

    submitting.value = true

    let response
    if (isEdit.value) {
      response = await updateNotice(form)
    } else {
      response = await addNotice(form)
    }

    if (response.code === 200) {
      proxy.$modal.showToast(isEdit.value ? '修改成功' : '新增成功')
      setTimeout(() => {
        handleBack()
      }, 1500)
    } else {
      proxy.$modal.showToast(response.msg || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    proxy.$modal.showToast('操作失败')
  } finally {
    submitting.value = false
  }
}

// 取消操作
function handleCancel() {
  proxy.$modal.confirm('确定要取消吗？未保存的内容将丢失。').then(() => {
    handleBack()
  })
}

// 返回上一页
function handleBack() {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>
@import '@/styles/edit-page.scss';

// 通知公告编辑页面特定样式
.notice-edit-page {
  // 可以添加通知公告特有的样式覆盖
}
</style>